<template>
  <view class="game-container">
    <view class="game-controls">
      <button class="game-control-btn control-btn" @tap="showSaveDialog" v-if="gameStatus !== 'checkmate' && gameStatus !== 'draw' && gameStatus !== 'timeout'">保存</button>
      <button class="control-btn" @tap="showLoadDialog" v-if="gameStatus === 'checkmate' || gameStatus === 'draw' || gameStatus === 'timeout'">读取</button>
      <button class="control-btn" @tap="showNewGameDialog" v-if="gameStatus !== 'playing'">新建游戏</button>
      <button class="control-btn" @tap="offerDraw" v-if="!drawOffered && gameStatus !== 'checkmate' && gameStatus !== 'draw' && gameStatus !== 'timeout'">提出和棋</button>
      <button class="control-btn" @tap="onUndoMove" v-if="canUndo && gameStatus !== 'checkmate' && gameStatus !== 'draw' && gameStatus !== 'timeout'">悔棋</button>
    </view>

    <view :class="['timer', 'top', currentPlayer === (isBlackOnTop ? 'black' : 'white') ? 'timer-active' : '']">
      <text class="player-name">{{ isBlackOnTop ? '黑方' : '白方' }}</text>
      <text class="time">{{ isBlackOnTop ? formattedBlackTime : formattedWhiteTime }}</text>
    </view>

    <view class="chessboard-container">
      <chessboard
        ref="chessboard"
        :board-matrix="boardMatrix"
        :language="userLanguage"
        :selected-piece="selectedPiece"
        :current-player="currentPlayer"
        :game-status="gameStatus"
        :is-interactive="isPlayerTurn"
        :possible-moves="gamePossibleMoves"
        @updateSelectedPiece="selectedPiece = $event"
        @pieceMoved="onPieceMoved"
        @check="onCheck"
        @checkmate="onCheckmate"
        @pawnPromotion="onPawnPromotion"
        @draw="onDraw"
        @drawOffer="onDrawOffer"
        @moveUndone="onMoveUndone"
        @updatePossibleMoves="handlePossibleMovesUpdate"
        @updateBoardMatrix="handleBoardUpdate"
        @pieceClick="handlePieceClick"
        @promotion-complete="handlePromotionComplete"
        @player-change="handlePlayerChange"
      />
    </view>

    <view :class="['timer', 'bottom', currentPlayer === (isBlackOnTop ? 'white' : 'black') ? 'timer-active' : '']">
      <text class="player-name">{{ isBlackOnTop ? '白方' : '黑方' }}</text>
      <text class="time">{{ isBlackOnTop ? formattedWhiteTime : formattedBlackTime }}</text>
    </view>

    <view class="player-info">
      <text>当前回合: {{ currentPlayer === 'white' ? '白方' : '黑方' }}</text>
    </view>



    <!-- Save Dialog -->
    <view class="dialog-overlay" v-if="isShowSaveDialog">
      <view class="dialog">
        <view class="dialog-title">保存游戏</view>
        <input
          class="dialog-input"
          v-model="saveName"
          placeholder="请输入存档名称"
        />
        <view class="dialog-buttons">
          <button class="dialog-btn" @tap="saveGame">保存</button>
          <button class="dialog-btn" @tap="isShowSaveDialog = false">取消</button>
        </view>
      </view>
    </view>

    <!-- Load Dialog -->
    <view class="dialog-overlay" v-if="isShowLoadDialog">
      <view class="dialog">
        <view class="dialog-title">加载游戏</view>
        <scroll-view class="save-list" scroll-y>
          <view
            v-for="item in saveList"
            :key="item.timestamp"
            class="save-list-item"
            :class="{ 'save-item-highlight': isSaveHover }"
            @touchstart="isSaveHover = true"
            @touchend="isSaveHover = false"
            @tap="loadGame(item.name)"
          >
            <view class="save-info">
              <text class="save-name">{{ item.name }}</text>
              <text class="save-time">{{ formatSaveTime(item.timestamp) }}</text>
            </view>
            <view
              class="save-delete"
              @tap.stop="deleteSave(item.name)"
            >删除</view>
          </view>
        </scroll-view>
        <view class="dialog-buttons">
          <button class="dialog-btn" @tap="isShowLoadDialog = false">关闭</button>
        </view>
      </view>
    </view>

    <!-- New Game Dialog -->
    <view class="dialog-overlay" v-if="isShowNewGameDialog">
      <view class="dialog">
        <view class="dialog-title">新建游戏</view>
        <view class="dialog-content">
          <view class="dialog-item">
            <text class="dialog-label">选择您的颜色：</text>
            <view class="color-options">
              <view class="color-option" :class="{ 'selected': playerColor === 'white' }" @tap="playerColor = 'white'">
                <image class="piece-preview" src="../../static/images/pieces/white_king.png" />
                <text>白方</text>
              </view>
              <view class="color-option" :class="{ 'selected': playerColor === 'black' }" @tap="playerColor = 'black'">
                <image class="piece-preview" src="../../static/images/pieces/black_king.png" />
                <text>黑方</text>
              </view>
            </view>
          </view>
          <view class="dialog-item">
            <text class="dialog-label">游戏时间（分钟）：</text>
            <view class="time-options">
              <view class="time-option" :class="{ 'selected': gameTime === 5 }" @tap="gameTime = 5">5</view>
              <view class="time-option" :class="{ 'selected': gameTime === 10 }" @tap="gameTime = 10">10</view>
              <view class="time-option" :class="{ 'selected': gameTime === 15 }" @tap="gameTime = 15">15</view>
              <view class="time-option" :class="{ 'selected': gameTime === 30 }" @tap="gameTime = 30">30</view>
            </view>
          </view>
        </view>
        <view class="dialog-buttons">
          <button class="dialog-btn" @tap="startNewGame">开始</button>
          <button class="dialog-btn" @tap="isShowNewGameDialog = false">取消</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      boardMatrix: Array(8).fill(null).map(() => Array(8).fill(null)),
      selectedPiece: null,
      currentPlayer: 'white',
      gameStatus: 'playing',
      isPlayerTurn: true,
      gamePossibleMoves: [],
      showPromotionDialog: false,
      promotionColor: null,
      promotionPosition: null,
      isShowSaveDialog: false,
      isShowLoadDialog: false,
      isShowNewGameDialog: false,
      saveName: '',
      saveList: [],
      isSaveHover: false,
      userLanguage: 'zh_CN',
      timer: null,
      whiteTime: 600, // 10分钟
      blackTime: 600,
      formattedWhiteTime: '10:00',
      formattedBlackTime: '10:00',
      drawOffered: false,
      canUndo: false,
      isBlackOnTop: true,
      playerColor: 'white',
      gameTime: 10
    }
  },
  created() {
  // 尝试获取系统语言设置
    try {
      const windowInfo = uni.getWindowInfo()
      const appBaseInfo = uni.getAppBaseInfo()
      if (appBaseInfo && appBaseInfo.language) {
        this.userLanguage = appBaseInfo.language
      }
    } catch (error) {
       console.warn('获取系统语言失败:', error)
      // 保持默认语言设置
    }
  },
  methods: {
    // 添加语言设置方法
    setLanguage(lang) {
      if (lang && typeof lang === 'string') {
        this.userLanguage = lang
      }
    },
    
    onPieceMoved(moveInfo) {
      this.handleMove(moveInfo)
    },

    handleMove(moveInfo) {
      this.switchPlayer()
    },

    switchPlayer() {
      const newPlayer = this.currentPlayer === 'white' ? 'black' : 'white'
      this.currentPlayer = newPlayer
      this.isPlayerTurn = true
    },

    // 修改将军事件处理
    onCheck(e) {
      const { color } = e
      this.gameStatus = 'check'
      this.checkedColor = color
      
      // 显示将军提示
      uni.showToast({
        title: `${color === 'white' ? '白方' : '黑方'}被将军！`,
        icon: 'none',
        duration: 1500
      })

      // 更新游戏状态
      this.checkGameStatus()
    },

    // 修改将死事件处理
    onCheckmate(e) {
      const { winner, reason } = e
      this.gameStatus = 'checkmate'
      this.checkmateReason = reason
      this.checkedColor = winner === 'white' ? 'black' : 'white'
      this.stopTimer()
      
      let message
      switch (reason) {
        case 'killed':
          message = `${winner === 'white' ? '白方' : '黑方'}获胜！\n原因：${winner === 'white' ? '黑王' : '白王'}被吃掉`
          break
        case 'absolute':
          message = `${winner === 'white' ? '白方' : '黑方'}获胜！\n原因：绝杀`
          break
        default:
          message = `${winner === 'white' ? '白方' : '黑方'}获胜！\n原因：将死`
      }

      uni.showModal({
        title: '游戏结束',
        content: message,
        showCancel: false
      })
    },
  
    // 修改游戏状态检查方法
    checkGameStatus() {
      const chessboard = this.$refs.chessboard
      
      // 检查是否将军
      const checkResult = chessboard.isKingInCheck(this.currentPlayer)
      if (checkResult.isCheck) {
        // 检查是否将死
        const checkmateResult = chessboard.isCheckmate(this.currentPlayer)
        if (checkmateResult && checkmateResult.isCheckmate) {
          const winner = this.currentPlayer === 'white' ? 'black' : 'white'
          this.onCheckmate({ 
            winner,
            reason: checkmateResult.reason || 'checkmate'
          })
          return
        }
        // 只是将军
        this.onCheck({ color: this.currentPlayer })
        return
      }
    },

    onDraw() {
      this.gameStatus = 'draw'
      uni.showModal({
        title: '游戏结束',
        content: '和棋',
        showCancel: false
      })
    },

    onDrawOffer() {
      this.drawOffered = true
      uni.showModal({
        title: '和棋提议',
        content: '对方提出和棋，是否接受？',
        success: (res) => {
          if (res.confirm) {
            this.onDraw()
          }
          this.drawOffered = false
        }
      })
    },

    onMoveUndone() {
      this.canUndo = false
      this.switchPlayer()
    },

    showSaveDialog() {
      this.isShowSaveDialog = true
    },

    showLoadDialog() {
      this.loadSaveList()
      this.isShowLoadDialog = true
    },

    showNewGameDialog() {
      this.isShowNewGameDialog = true
      this.playerColor = 'white'
      this.gameTime = 10
    },

    startNewGame() {
      this.boardMatrix = Array(8).fill(null).map(() => Array(8).fill(null))
      this.selectedPiece = null
      this.currentPlayer = 'white'
      this.gameStatus = 'playing'
      this.isPlayerTurn = true
      this.gamePossibleMoves = []
      this.showPromotionDialog = false
      this.promotionColor = null
      this.promotionPosition = null
      this.drawOffered = false
      this.canUndo = false

      // 初始化棋盘
      this.$refs.chessboard.initBoard()
      // 获取并更新棋盘状态
      this.boardMatrix = this.$refs.chessboard.localBoardMatrix

      // 根据选择的时间设置计时器
      const timeInSeconds = this.gameTime * 60
      this.whiteTime = timeInSeconds
      this.blackTime = timeInSeconds
      this.formatTime()
      if (this.timer) {
        clearInterval(this.timer)
      }
      this.startTimer()

      this.isShowNewGameDialog = false

      uni.showToast({
        title: '新游戏开始',
        icon: 'success'
      })
    },

    // 处理兵升变事件
    onPawnPromotion(position) {
      this.promotionPosition = position
      this.promotionColor = this.currentPlayer
      this.showPromotionDialog = true
      this.isPlayerTurn = false
    },

    handlePossibleMovesUpdate(newMoves) {
      this.gamePossibleMoves = newMoves
    },

    handleBoardUpdate(newMatrix) {
      console.groupCollapsed('[棋盘更新] 接收更新')
      console.log('新矩阵:', JSON.stringify(newMatrix))
      this.boardMatrix = newMatrix
      this.$nextTick(() => {
        console.log('棋盘已更新')
      })
      console.groupEnd()
    },

    onSettingsUpdated(settings) {
      this.loadSettings()
    },

    handlePieceClick(piece) {
      if (this.gameStatus === 'checkmate' || this.gameStatus === 'draw') return
      
      if (piece.color !== this.currentPlayer) {
        uni.showToast({
          title: '请等待对方回合',
          icon: 'none'
        })
        return
      }
    },

    handlePromotionComplete() {
      this.isPlayerTurn = true
    },

    handlePlayerChange(newPlayer) {
      this.currentPlayer = newPlayer
      this.isPlayerTurn = true
      
      if (this.timer) {
        this.stopTimer()
        this.timer = setInterval(() => {
          if (this.currentPlayer === 'white') {
            this.whiteTime = Math.max(0, this.whiteTime - 1)
          } else {
            this.blackTime = Math.max(0, this.blackTime - 1)
          }
          this.formatTime()
        }, 1000)
      }
    },

    formatTime() {
      this.formattedWhiteTime = this.formatTimeValue(this.whiteTime)
      this.formattedBlackTime = this.formatTimeValue(this.blackTime)
    },

    formatTimeValue(seconds) {
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
    },

    startTimer() {
      this.timer = setInterval(() => {
        if (this.currentPlayer === 'white') {
          this.whiteTime = Math.max(0, this.whiteTime - 1)
        } else {
          this.blackTime = Math.max(0, this.blackTime - 1)
        }
        this.formatTime()

        if (this.whiteTime === 0 || this.blackTime === 0) {
          this.handleTimeout()
        }
      }, 1000)
    },

    stopTimer() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },

    handleTimeout() {
      this.stopTimer()
      this.gameStatus = 'timeout'
    },

    offerDraw() {
      if (this.gameStatus !== 'playing') return
      
      this.drawOffered = true
      this.$refs.chessboard.$emit('drawOffer')
      
      uni.showModal({
        title: '和棋提议',
        content: '已向对方发出和棋提议',
        showCancel: false
      })
    }
  }
}
</script>

<style src="./game.css"></style>
<style>
.color-options {
  display: flex;
  justify-content: space-around;
  margin: 10px 0;
}

.color-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  border-radius: 8px;
  border: 2px solid transparent;
  cursor: pointer;
}

.color-option.selected {
  border-color: #4CAF50;
  background-color: rgba(76, 175, 80, 0.1);
}

.piece-preview {
  width: 40px;
  height: 40px;
  margin-bottom: 5px;
}

.time-options {
  display: flex;
  justify-content: space-around;
  margin: 10px 0;
}

.time-option {
  padding: 10px 20px;
  border-radius: 4px;
  border: 1px solid #ccc;
  cursor: pointer;
}

.time-option.selected {
  background-color: #4CAF50;
  color: white;
  border-color: #4CAF50;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  width: 80%;
  max-width: 400px;
}

.dialog-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  text-align: center;
}

.dialog-content {
  margin-bottom: 20px;
}

.dialog-item {
  margin-bottom: 15px;
}

.dialog-label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}

.dialog-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.dialog-btn {
  min-width: 80px;
  padding: 8px 15px;
  border-radius: 4px;
  background-color: #4a90e2;
  color: white;
  border: none;
}

.dialog-btn:active {
  background-color: #357abd;
}
</style>